package server

import (
	"context"
	"fmt"
	rpcxLog "github.com/smallnest/rpcx/log"
	"github.com/smallnest/rpcx/server"
	"gogame/logger"
	"gogame/server/rpcx"
	"net"
	"time"
)

type RpcXServer struct {
	rpcx.RpcXStruct
	RpcServer           *server.Server
	RouteFunc           func()         // 服务路由注册
	HandleConnCloseFunc func(net.Conn) // 处理client断开逻辑
}

// NewRpcXServer 实例化NewRpcXServer
func NewRpcXServer(listen, serviceName string) *RpcXServer {
	return &RpcXServer{
		RpcXStruct: rpcx.RpcXStruct{
			BasePath:    rpcx.GetServerBasePath(),
			Type:        "rpcServer",
			ServiceName: serviceName,
			Name:        fmt.Sprintf("rpcServer[%s]", listen),
			Address:     listen,
		},
	}
}

func (s *RpcXServer) Listen(network, addr string) {
	// 禁止rpcx自带log
	rpcxLog.SetDummyLogger()

	// 实例化server
	s.RpcServer = server.NewServer()
	// 中间件处理
	AddPlugin(s)
	// 路由
	s.RouteFunc()

	//服务开启
	err := s.RpcServer.Serve(network, addr)
	if err != nil {
		logger.Print("%s Listener end->%s", s.ServiceName, err)
	}

}

// HandleConnClose rpcXClient链接断开
func (s *RpcXServer) HandleConnClose(conn net.Conn) bool {
	go s.HandleConnCloseFunc(conn)
	return true
}

// Close rpcServer链接断开
func (s *RpcXServer) Close() {
	_ctx, _ := context.WithTimeout(context.Background(), time.Second*2)
	err := s.RpcServer.Shutdown(_ctx)
	if err != nil {
		logger.Print("%s Close end->%s", s.ServiceName, err)
	}
}
